using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Framework.Extensions
{
    public static class ObjectExtensions
    {
        public static TResult Maybe<TObject, TResult>(this TObject? source, Func<TObject, TResult> evaluate)
            where TObject : struct 
        {
            if (null == source)
            {
                return default(TResult);
            }
            return evaluate(source.Value);
        }

        public static TResult Maybe<TObject, TResult>(this TObject source, Func<TObject, TResult> evaluate)
            where TObject : class
        {
            if (null == source)
            {
                return default(TResult);
            }
            return evaluate(source);
        }
        
        public static TResult Maybe<TObject, TResult>(this TObject source, Func<TObject, TResult> evaluate, TResult ifNullResult)
            where TObject : class
        {
            if (null == source)
            {
                return ifNullResult;
            }
            return evaluate(source);
        }

        public static void Maybe<TObject>(this TObject source, Func<TObject, bool> condition, Action<TObject> action)
            where TObject : class
        {
            if (null == source)
            {
                return;
            }
            if (condition(source)) action(source);
        }
        
        public static void Maybe<TObject>(this TObject source, Action<TObject> action)
            where TObject : class
        {
            if (null == source)
            {
                return;
            }
            action(source);
        }

        public static TObject Do<TObject>(this TObject source, Action<TObject> action)
            where TObject : class
        {
            source.Maybe(action);
            return source;
        }
    }
}